// /src/router/guards/auth.ts
import type { NavigationGuard } from 'vue-router'
import { useAppStore } from '@/stores/appStore'

export const authGuard: NavigationGuard = (to, from, next) => {
  const store = useAppStore()
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth && !store.user) {
    next('/login')
    return
  }
  
  // 检查管理员权限
  if (to.meta.requiresAdmin && !store.user?.isAdmin) {
    // 使用原生alert替代ElMessage
    alert('无权访问该页面')
    next(from.path)
    return
  }
  
  // 更新当前激活菜单
  if (to.name) {
    store.setActiveMenu(to.name as string)
  }
  
  // 设置页面标题
  if (to.meta.title) {
    store.setPageTitle(to.meta.title as string)
  }
  
  next()
}